﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MacomberMapSystem.Common.Database;
using System.Net;

namespace MacomberMapSystem.Common.User_Interfaces.Database
{
    /// <summary>
    /// This form provides editing of the user profile
    /// </summary>
    public partial class frmUserProfileEditor : Form
    {
        #region Variable declarations
        /// <summary>The user being edited</summary>
        public MM_Database_User EditingUser;

        /// <summary>The database from which the user was located</summary>
        public MM_Database_Connector Db;

        /// <summary>The image to be drawn</summary>
        public Image DrawImage;

        /// <summary>The zoom for drawing the image</summary>
        public float DrawPercentage;

        /// <summary>The offset X amount</summary>
        public float OffsetX;

        /// <summary>The offset Y amount</summary>
        public float OffsetY;

        /// <summary>
        /// The point at which the mouse was pressed down
        /// </summary>
        private Point MouseDownPoint;
        #endregion

        
        /// <summary>
        /// Initialize a new user window
        /// </summary>
        public frmUserProfileEditor(MM_Database_User User, MM_Database_Connector Db)
        {
            InitializeComponent();
            this.Text = User.FullName + " - [" + Application.ProductName + "]";
            this.Db = Db;
            this.EditingUser = User;
            lblUserNameValue.Text = User.UserName;
            txtEmail.Text = User.Email;
            txtFullName.Text = User.FullName;
            txtNickname.Text = User.Nickname;
            txtNote.Text = User.UserNote;
            chkDisplaycleanups.Checked = User.HandleWarnings;
            chkTopologyChanges.Checked = User.HandleErrors;
            if (User.UserImage != null)
            {
                DrawImage = User.UserImage;
                DrawPercentage = 1f;
            }
            else
                foreach (String str in "Employees,Contractors".Split(','))
                    foreach (String str2 in ".jpg,.bmp,.png".Split(','))
                        foreach (String EmpName in new string[] { User.Nickname ,User.FullName.Split(' ')[0]})
                    try
                    {
                        //Try to retrieve the user information from Sharepoint
                        String[] splStr = User.FullName.Split(' ');
                        HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create("[SharepointHRDirectory]" + splStr[1] + ",%20" + EmpName + str2);
                        wReq.UseDefaultCredentials = true;
                        HttpWebResponse wResp = (HttpWebResponse)wReq.GetResponse();
                        using (Stream ReadStream = wResp.GetResponseStream())
                        {
                            DrawImage = Image.FromStream(ReadStream);
                            DrawPercentage = 64f / (float)Math.Max(DrawImage.Width, DrawImage.Height);
                        }
                    }
                    catch (Exception)
                    { 
                    }

            //Create our status list
            foreach (String Name in Enum.GetNames(typeof(MM_Database_User.enumUserState)))
                if (User.UserState.ToString() == Name)
                    cmbState.SelectedIndex = cmbState.Items.Add(Name);
                else
                    cmbState.Items.Add(Name);

        }

        /// <summary>
        /// Load a new image into place
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoad_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog oFd = new OpenFileDialog())
            {
                oFd.Title = "Open a user image";
                oFd.Filter = "JPEG Image (*.jpg)|*.jpg";
                if (oFd.ShowDialog() == DialogResult.OK)
                    try
                    {                        
                        //Determine our percentage
                        DrawImage = Image.FromFile(oFd.FileName);
                        DrawPercentage = 64f / (float)Math.Max(DrawImage.Width, DrawImage.Height);
                        picImage.Refresh();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Unable to open file " + Path.GetFileNameWithoutExtension(oFd.FileName) + ": " + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
            }

        }

    


        /// <summary>
        /// Handle zooming in
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomIn_Click(object sender, EventArgs e)
        {
            this.DrawPercentage+=0.025f;
            picImage.Refresh();
        }

        /// <summary>
        /// Handle zooming out
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomOut_Click(object sender, EventArgs e)
        {
            this.DrawPercentage -= 0.025f;
            picImage.Refresh();
        }

        /// <summary>
        /// Redraw the picture image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picImage_Paint(object sender, PaintEventArgs e)
        {
            
            //Now, based on our percentages, determine our starting position
            e.Graphics.Clear(Color.Black);
            if (DrawImage == null)
                return; 
            float StartX = OffsetX / DrawPercentage;
            float StartY = OffsetY / DrawPercentage;
            float ZoomWidth = 64 / DrawPercentage;
            e.Graphics.DrawImage(DrawImage, new Rectangle(0, 0, 64, 64), new RectangleF(StartX, StartY, ZoomWidth, ZoomWidth), GraphicsUnit.Pixel);
           

        }

        /// <summary>
        /// Handle the mouse being pressed down in the user's image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picImage_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                MouseDownPoint = Cursor.Position;

        }

        /// <summary>
        /// Handle the mouse being moved in the user's image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picImage_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                OffsetX = MouseDownPoint.X - Cursor.Position.X;
                OffsetY = MouseDownPoint.Y - Cursor.Position.Y;
                picImage.Refresh();
            }
        }

        /// <summary>
        /// When the user hits OK, set everything back
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            EditingUser.Email = txtEmail.Text;
            EditingUser.FullName = txtFullName.Text;
            EditingUser.Nickname = txtNickname.Text;
            EditingUser.UserNote = txtNote.Text;
            EditingUser.HandleErrors = chkTopologyChanges.Checked;
            EditingUser.HandleWarnings= chkDisplaycleanups.Checked;
            Bitmap OutBitmap = new Bitmap(64,64);
            using (Graphics g = Graphics.FromImage(OutBitmap))
            picImage_Paint(this, new PaintEventArgs(g, new Rectangle(0,0,64,64)));
            EditingUser.UserImage = OutBitmap;
            EditingUser.UserState = (MM_Database_User.enumUserState)Enum.Parse(typeof(MM_Database_User.enumUserState), cmbState.Text);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
